<template>
	<view class="grace-padding">

		<view style="margin-top:50px; font-size: 50upx; height: 180upx; color:#417dc9 ;" class="grace-center">
			领域知识服务
		    <!-- <image src='../../../static/logo.png' style='width:68px; height:68px; border-radius:8px;'></image> -->
		</view>

		<view class="grace-form" style="margin-top:50upx;">
			<form @submit="registNow">
				<view class="grace-items grace-items-wbg item-border">
					<view class="grace-label">
						<picker :value="pnpre" @change="changePre" :range="pnpres" name="pn_pre">
							<text>+{{pnpre}}</text>
						</picker>
					</view>
					<input type="number" name="name" class="input" placeholder="请输入手机号"></input>
				</view>
				<view class="grace-space-between" style="margin-top:28upx;">
					<view class="grace-items grace-items-wbg item-border" style="width:100%;">
						<view class="grace-label grace-center">密码：</view>
						<input class="input" name="password" :password="showPassword" placeholder="请输入密码"></input>
						<view style="margin:8px 5px;" class="uni-icon uni-icon-eye" :class="[!showPassword ? 'uni-active' : '']" @click="changePassword"></view>
					</view>
				</view>
				<view class="grace-space-between" style="margin-top:28upx;">
					<view class="grace-items grace-items-wbg" style="width:66%;">
						<view class="grace-label grace-center">验证码：</view>
						<input class="input" name="code" placeholder="输入0000"></input>
					</view>
					<view style="width:32%;  margin-left:2%; paading:0;">
						<button type="primary" class="thisBtn" style='background:#417dc9;'>获取验证码</button>
					</view>
				</view>
				<button form-type='submit' type='primary' style='background:#417dc9; margin-top:20px;'>
					注 册
				</button>
			</form>
		</view>

		<view class="grace-center" style="margin-top:20upx; color:#000; line-height:50upx;" @click="goLogin()">
			已注册账号？点击登录
		</view>

		<!-- 第三方登录 -->
		<!-- 		<view class="grace-login-three" style="margin-top:30px;">
			<view class="grace-iconfont icon-weixin" @tap="loginWithWx"></view>
			<view class="grace-iconfont icon-qq"></view>
			<view class="grace-iconfont icon-weibo"></view>
		</view> -->
        <view class="oauth-row" v-bind:style="{top: positionTop + 'px'}">
			<!--#ifdef MP-WEIXIN-->
				<button class="wx-btn" open-type="getUserInfo" @click="loginWith('weixin')">
					<image src="../../../static/weixin.png" mode="widthFix"></image>
				</button>
			<!--#endif-->
			<!-- #ifndef MP-WEIXIN -->
            <view class="oauth-image" v-for="provider in providerList" :key="provider.value">
                <image :src="provider.image" @tap="loginWith(provider.value)"></image>
            </view>
			<!--#endif-->
        </view>

	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		computed: {
			...mapState(['userInfo', 'hasLogin', 'loginProvider', 'openid'])
		},
		data() {
			return {
				pnpre: '86',
				pnpres: ['86', '01', '11', '26', '520'],
				showPassword: true,
				providerList: [],
				positionTop: 0,
				url: ""
			}
		},
		onLoad(e) {
			if (e.url != undefined) {
				this.url = e.url;
			}
			this.initPosition();
			this.initProvider();
		},
		methods: {
			...mapMutations(['login', 'logout', 'setOpenid', 'setProvider']),
			initProvider() {
				const filters = ['weixin', 'qq', 'sinaweibo'];
				uni.getProvider({
					service: 'oauth',
					success: (res) => {
						if (res.provider && res.provider.length) {
							for (let i = 0; i < res.provider.length; i++) {
								if (~filters.indexOf(res.provider[i])) {
									this.providerList.push({
										value: res.provider[i],
										image: '../../../static/' + res.provider[i] + '.png'
									});
								}
							}
						}
					},
					fail: (err) => {
						console.error('获取服务供应商失败：' + JSON.stringify(err));
					}
				});
			},
			initPosition() {
				/**
				 * 使用 absolute 定位，并且设置 bottom 值进行定位。软键盘弹出时，底部会因为窗口变化而被顶上来。
				 * 反向使用 top 进行定位，可以避免此问题。
				 */
				this.positionTop = uni.getSystemInfoSync().windowHeight - 100;
			},
			changePassword: function() {
				this.showPassword = !this.showPassword;
			},
			loginWith: function(value) {
				var that = this;
				uni.login({
				  provider: value,
				  success: function (loginRes) {
					var code = "";
					if(loginRes.code!=undefined){
						uni.request({
							url: 'https://api.weixin.qq.com/sns/jscode2session?appid='+that.appid+'&secret='+that.secret+'&js_code=' +
								loginRes.code + '&grant_type=authorization_code',
							method: 'GET',
							data: {},
							success(res) {
								that.findUser(value,res.data.openid);	
							},
						});				
					}else{
						that.findUser(value,loginRes.authResult.openid);	
					}
				  }
				});
			},
			changePre: function(e) {
				this.pnpre = this.pnpres[e.detail.value];
			},
			findUser(value,openid){
				var that = this;
				var data ={};		
				// #ifdef MP-WEIXIN
					data.connectSmartprogram=openid;
				// #endif
				// #ifndef MP-WEIXIN
					if (value == "weixin") {
						data.connectWeixin=openid;
					}else if (value == "qq") {
						data.connectQq=openid;
					} else if (value == "sinaweibo") {
						data.connectSina=openid;
					}
				// #endif					
				uni.request({
					url: this.serverUrl + 'user-api/findUser',
					header: {
						"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
					},
					method: 'POST',
					data: data,
					success: (r) => {
						if (r.data.code == "000000") {
							if(r.data.data==null){
								uni.getUserInfo({
								  provider: value,
								  success: function (infoRes) {
									uni.navigateTo({
										url: "../binding/binding?url="+that.url+"&openid="+openid+"&provider="+value+"&userInfo="+encodeURIComponent(JSON.stringify(infoRes.userInfo))
									})
								  }
								});	
							}else{
								this.login(r.data.data);
								var date = new Date();
								uni.setStorageSync('appKey', r.data.data.username + '&' + date.getTime());
								if (this.url != "") {
									uni.redirectTo({
										url: this.url
									})
								} else {
									uni.switchTab({
										url: "/pages/tab-bar/my/my",
									})
								}
							}
						} else {
							uni.showToast({
								title: r.errMsg
							});
						}
					},
					fail: (err) => {
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						})
					}
				})				
			},				
			registNow: function(e) {
				//console.log(e);
				if (e.detail.value.name.length < 1) {
					uni.showToast({
						title: "请输入手机号",
						icon: "none"
					})
					return;
				}
				var reg = /^[1][3,4,5,7,8][0-9]{9}$/;
				if (!reg.test(e.detail.value.name)) {
					uni.showToast({
						title: "手机号格式不正确",
						icon: "none"
					})
					return;
				}
				if (e.detail.value.password.length < 6 || e.detail.value.password.length > 20) {
					uni.showToast({
						title: "密码长度请设置为6-20位",
						icon: "none"
					})
					return;
				}
				// 				if(e.detail.value.code.length < 1){
				// 					uni.showToast({
				// 						title:"请输入验证码",
				// 						icon:"none"
				// 					})
				// 					return;
				// 				}					
				uni.request({
					url: this.serverUrl + 'user-api/register',
					header: {
						"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
					},
					method: 'POST',
					data: {
						username: e.detail.value.name,
						password: e.detail.value.password,
						code: e.detail.value.code,
					},
					success: (r) => {
						//console.log(r);
						if (r.data.code == '000000') {
							if (r.data.data.id != null) {
								this.login(r.data.data);
								var date = new Date();
								uni.setStorageSync('appKey', r.data.data.username + '&' + date.getTime());
								if (this.url != "") {
									uni.redirectTo({
										url: this.url
									})
								} else {
									uni.switchTab({
										url: "/pages/tab-bar/my/my",
									})
								}
							} else {
								uni.showToast({
									title: '验证码不正确',
									icon: 'none'
								})
							}
						} else {
							uni.showToast({
								title: r.data.message
							});
						}
					},
					fail: (err) => {
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						})
					}
				})
			},
			goLogin() {
				uni.navigateTo({
					url: "/pages/general/login/login"
				})
			},
			goRegister() {
				uni.navigateTo({
					url: "/pages/general/register/register"
				})
			}
		}
	}
</script>

<style>
	page {
		width: 750upx;
		min-height: 100%;
	}

	.thisBtn {
		/* background: #5D6AB4; */
		color: #FFFFFF;
		font-size: 14px;
		width: 100%;
		height: 88upx;
		line-height: 88upx;
	}

	.item-border {
		border-bottom: 1px solid #E0E0E0 !important;
	}

	.login-sendmsg-btn {
		border: 1px solid #00C777 !important;
		background: none !important;
		color: #00C777 !important;
		width: 100%;
		height: 35px;
		line-height: 35px;
		margin-top: 6px;
		font-size: 14px !important;
	}

	.grace-login-three {
		display: flex;
		justify-content: center;
		flex-wrap: nowrap;
	}

	.grace-login-three view {
		width: 50px;
		height: 50px;
		line-height: 50px;
		font-size: 46px;
		color: #00C777;
		text-align: center;
		margin: 8px 15px;
	}

	.grace-form picker {
		text-align: left;
	}

	.grace-form .grace-items .input {
		padding: 10upx 2%;
		margin-left: 15upx;
	}

	.oauth-row {
		display: flex;
		flex-direction: row;
		justify-content: center;
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
	}

	.oauth-image {
		width: 100upx;
		height: 100upx;
		border: 1upx solid #dddddd;
		border-radius: 100upx;
		margin: 0 40upx;
		background-color: #ffffff;
	}

	.oauth-image image {
		width: 60upx;
		height: 60upx;
		margin: 20upx;
	}
	
	.wx-btn {
		padding: 0;
		margin: 0;
		background: none !important;
		color: #fff !important;
	}
	.wx-btn::after{ 
		border: none; 
	}
	.wx-btn image{
		width: 100upx;
	}
	
</style>
